package ro.cuzma.larry.bookscollection.persistance.xml;

import ro.cuzma.larry.bookscollection.md.Author;
import ro.cuzma.larry.bookscollection.md.Book;
import ro.cuzma.larry.persistance.common.Entity;
import ro.cuzma.larry.persistance.common.EntityIdAndValue;
import ro.cuzma.larry.persistance.xml.XMLNode;
import ro.cuzma.larry.persistance.xml.XMLTagValue;
import ro.cuzma.larry.persistance.xml.XMLTagValueList;
import ro.cuzma.larry.persistance.xml.XMLUtil;
import ro.cuzma.larry.persistance.xml.exception.XMLException;

public class BookHelper extends XMLNode {

    private XMLTagValue                             id;
    private XMLTagValue                             name;
    private XMLTagValue                             languageID;
    private XMLTagValue                             aquireDate;
    private XMLTagValueList<EntityIdAndValue<Long>> authors;

    public XMLTagValue getId() {
        return id;
    }

    public XMLTagValue getAquireDate() {
        return aquireDate;
    }

    public XMLTagValue getName() {
        return name;
    }

    public XMLTagValue getLanguageID() {
        return languageID;
    }

    public XMLTagValueList<EntityIdAndValue<Long>> getAuthors() {
        return authors;
    }

    public BookHelper() {
        super(XMLTags.BOOK);
    }

    public BookHelper(Book book) throws XMLException {
        super(XMLTags.BOOK, book);
    }

    @Override
    public boolean toSave() {
        return id.toSave();
    }

    @Override
    protected void initTags() {
        id = new XMLTagValue(XMLTags.BOOK_ID, null);
        name = new XMLTagValue(XMLTags.BOOK_NAME, null);
        languageID = new XMLTagValue(XMLTags.LANGUAGEID);
        aquireDate = new XMLTagValue(XMLTags.BOOK_AQUIREDATE);
        authors = new XMLTagValueList<EntityIdAndValue<Long>>(XMLTags.BOOK_AUTHORS,
                XMLTags.AUTHORID);
        xmlObjects.add(id);
        xmlObjects.add(name);
        xmlObjects.add(aquireDate);
        xmlObjects.add(languageID);
        xmlObjects.add(authors);

    }

    @Override
    protected void initWithEntity(Entity<?> entity) {
        Book book = (Book) entity;
        id.setValue(book.getId().toString());
        name.setValue(book.getName());
        if (book.getLanguage() != null) {
            languageID.setValue(book.getLanguage().getId().toString());
        }
        XMLTagValue xmlTag;
        for (Author author : book.getAuthors().getEntityList()) {
            xmlTag = new XMLTagValue(XMLTags.AUTHORID, author.getId().toString());
            authors.add(xmlTag);
        }
        if (book.getAquireDate() != null) {
            aquireDate.setValue(XMLUtil.convertGregorianCalendar(book.getAquireDate(), null));
        }

    }
}
